const createError = require('http-errors');
const express = require('express');
const path = require('path');//开放upload静态文件
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { expressjwt } = require("express-jwt"); // jwt解析
const jwtSecretKey = require("./utils/jwtSecretKey"); // 加密、解密密钥
const cors = require("cors"); // 跨域

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');  // 用户
const societiesRouter = require('./routes/societies');  // 社团
const societyTypesRouter = require('./routes/societyTypes');  // 社团类型
const societyAppliesRouter = require('./routes/societyApplies');  // 社团申请
const goodsRouter = require('./routes/goods');  // 物资
const goodsAppliesRouter = require('./routes/goodsApplies');  // 物资申请
const goodsRecordsRouter = require('./routes/goodsRecords');  // 物资记录
const suggestionsRouter = require('./routes/suggestions');  // 留言/建议
const summariesRouter = require('./routes/summaries');  // 活动总结
const collegesRouter = require('./routes/colleges');  // 基础信息-学院
const majorsRouter = require('./routes/majors');  // 基础信息-专业
const gradesRouter = require('./routes/grades');  // 基础信息-年级
const scoresRouter = require('./routes/scores');  // 二课分
const uploadRouter = require('./routes/upload');  // 上传文件
const emailRouter = require('./routes/email');  // 上传文件
const uploadQiniuRouter = require('./routes/uoloadQiniu') // 上传七牛云
const activityRouter = require('./routes/activities'); // 活动管理
const notificationRouter = require('./routes/notifications'); // 校级通知
const screenRouter = require('./routes/screen'); // 大屏接口




const app = express();


// 跨域设置
app.all("*", function (req, res, next) {
  res.setHeader("Access-Control-Allow-Credentials", true);
  // res.setHeader("Access-Control-Allow-Origin", req.get("Origin")); // 添加这一行代码，代理配置不成功
  res.setHeader("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE, PUT');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since")
  next();
})


// 前置守卫-解析jwt,token认证
app.use(
  expressjwt({
    secret: jwtSecretKey.jwtSecretKey,
    algorithms: ["HS384"],
  }).unless({
    path: ["/dev-api/users/login", "/dev-api/users/register",'/dev-api/email','/dev-api/users/password'],
  })
);

app.use(function (err, req, res, next) {
  console.log(req.headers.authorization);
  if (err.name === "UnauthorizedError") {
    res.status(401).json({
      code: 401,
      msg: "无效的token或没有传递token,请重新登录",
    });
  } else {
    next(err);
  }
});

app.use(logger('dev'));
app.use(express.json())
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'upload')));
app.use(cors());

app.use('/dev-api/', indexRouter);
app.use('/dev-api/users', usersRouter);
app.use('/dev-api/societies', societiesRouter)
app.use('/dev-api/societyTypes', societyTypesRouter)
app.use('/dev-api/societyApplies', societyAppliesRouter)
app.use('/dev-api/goods', goodsRouter);
app.use('/dev-api/goodsApplies', goodsAppliesRouter);
app.use('/dev-api/goodsRecords', goodsRecordsRouter);
app.use('/dev-api/suggestions', suggestionsRouter);
app.use('/dev-api/summaries', summariesRouter);
app.use('/dev-api/colleges', collegesRouter);
app.use('/dev-api/majors', majorsRouter);
app.use('/dev-api/grades', gradesRouter);
app.use('/dev-api/scores', scoresRouter);
app.use('/dev-api/upload', uploadRouter);
app.use('/dev-api/email', emailRouter);
app.use('/dev-api/uploadQiniu', uploadQiniuRouter);
app.use('/dev-api/activity', activityRouter);
app.use('/dev-api/notification', notificationRouter);
app.use('/dev-api/screen', screenRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
